/**
 * 部门选择器
 */
import React from 'react';
import { TreeSelect } from 'antd';
import { useRequest } from '@/hooks';
import { connect } from 'umi';
import { fetchOrg } from '../service';

const getTreeData = (data = [], fieldsName = { value: 'organizationCode', title: 'organizationName' }) =>
    data?.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        children: item.children ? getTreeData(item.children, fieldsName) : item.children
    }));

function Department({ user, code, value, onChange }) {
    const { firstOrgInfo } = user;
    const { firstCompanyPath } = firstOrgInfo;
    const { data } = useRequest(() =>
        fetchOrg({
            parentOrganizationPathLike: code || firstCompanyPath,
            showTreeFlag: 1,
            organizationType: 3
        })
    );

    const treeData = React.useMemo(() => {
        const finalData = Array.isArray(data?.data) ? data?.data : [];
        return getTreeData(finalData);
    }, [data]);

    return (
        <TreeSelect
            value={value}
            onChange={_value => {
                onChange(_value);
            }}
            style={{ width: 200 }}
            allowClear
            maxTagCount={1}
            treeData={treeData}
            placeholder="请选择"
        />
    );
}

export default connect(({ user }) => ({ user: user.currentUser }))(Department);
